from django.shortcuts import render

# Create your views here.

from django.views import View
from django.http import JsonResponse
from QQLoginTool.QQtool import OAuthQQ


class QQLoginView(View):
    def get(self, request):
        # 1. 获取参数
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '没有code信息'})
        # QQ登录参数
        # 我们申请的 客户端id
        QQ_CLIENT_ID = '101474184'
        # 我们申请的 客户端秘钥
        QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'
        # 我们申请时添加的: 登录成功后回调的路径
        QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'

        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI,
                     state=next)
        # 2. 通过code获取token
        token = qq.get_access_token(code)
        # 3. 通过token获取openid
        openid = qq.get_open_id(token)
        # 4. 根据openid进行数据的查询
        from apps.oauth.models import OAuthQQUser
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果查询不出用户信息, 说明没有绑定过 我们要把openid,以响应的形式 给前端页面


            from apps.oauth.common import generic_open_id
            secret_openid = generic_open_id(openid)

            return JsonResponse({'code':200,'access_token':secret_openid})
        else:
            from django.contrib.auth import login
            # 如果查询出 用户信息, 说明用户之前绑定过 设置状态保持 跳转到指定页面
            login(request,user=qquser.user)

            # 0表示已经绑定过了
            return JsonResponse({'code': 0})

    def post(self,request):
        # 1. 接收参数 --json
        import json
        data = json.loads(request.body.decode())
        # 2. 提取参数
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        secret_data = data.get('access_token')

        # 解密
        from apps.oauth.common import check_open_id
        openid = check_open_id(secret_data)
        if openid is None:
            return JsonResponse({'code':400,'errmsg':'参数错误'})
        # 3. 验证参数 -- 验证手机号 验证密码 验证短信验证码
        # 验证短信验证码
        # 3.1 连接redis
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        # 3.2 获取redis的短信验证码
        redis_sms_code = redis_cli.get(mobile)
        # 3.3 比对
        if redis_sms_code is None:
            return JsonResponse({'code':400,'errmsg':'短信验证码过期'})
        if redis_sms_code.decode() != sms_code:
            return JsonResponse({'code':400,'errmsg':'短信验证码错误'})
        # 4. 根据手机号判断用户信息
        from apps.users.models import User
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 如果没有查询到 则新增一个用户
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 如果查询到 则验证密码是否正确
            # user.check.password是父类的一个方法,系统为我们提供的 验证密码的方法
            if not user.check_password(password):
                # 密码不正确,返回错误的相响应
                return JsonResponse({'code':400,'errmsg':'绑定失败'})
        # 5. 绑定用户信息(数据入库)
        from apps.oauth.models import OAuthQQUser
        OAuthQQUser.objects.create(openid=openid,user=user)
        # 6. 状态保持
        from django.contrib.auth import login
        login(request,user)
        # 7. 设置cookie
        response = JsonResponse({'code':0,'errmsg':'ok'})
        response.set_cookie('username',user.username,max_age=24*3600)
        # 8. 返回响应
        return response
# """
# ######加密######################
# # 1. 导入
# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# # 2. 创建实例对象
# s = Serializer(secret_key='123', expires_in=3600)
# # 3. 组织数据,然后加密
# data = {
#     'openid':'abc'
# }
# s.dumps(data)
#
# ########解密########################
# # 1. 导入
# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# from itsdangerous import BadSignature
# # 2. 创建实例对象
# try:
#     s = Serializer(secret_key='123', expires_in=3600)
#     # 3. 解密数据
#     s.loads('yJhbGciOiJIUzUxMiIsImlhdCI6MTYxOTYwMzM2NiwiZXhwIjoxNjE5NjA2OTY2fQ.eyJvcGVuaWQiOiJhYmMifQ.bpUelhbw_LljZ1joixouoSka-7f9kVNws7h52erp5Q_A17nsI6nunmm1fx9uHHrCUcQJpbbSvJ2af4Lx1EqaIQ')
# except BaseException:
#     print('数据被修改')
#
# """




